package com.example.easypoi.controller;

import com.example.easypoi.entity.Contract;
import com.example.easypoi.entity.Userdoc;
import com.example.easypoi.service.WordExportService;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jeecgframework.poi.word.entity.WordImageEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/word")
public class WordExportController {

    @Autowired
    private WordExportService wordService;

    @GetMapping("/export/entity")
    public void exportWithEntity(HttpServletResponse response) throws IOException {
        Userdoc user = new Userdoc("张三", 30,
                new WordImageEntity("static/avatar.png", 100, 100));

        XWPFDocument doc = wordService.exportWordWithImage("contract_template.docx", user);
        writeResponse(doc, response, "user.docx");
    }

    @GetMapping("/export/map")
    public void exportWithMap(HttpServletResponse response) throws IOException {
        List<Contract> contracts = List.of(
                new Contract("HT001", new BigDecimal("1000"), "2025-08-24"),
                new Contract("HT002", new BigDecimal("2000"), "2025-08-25")
        );

        XWPFDocument doc = wordService.exportWordWithTable("contract_template.docx", contracts);
        writeResponse(doc, response, "contracts.docx");
    }

    @GetMapping("/template/{type}")
    public ResponseEntity<Resource> downloadTemplate(@PathVariable String type) throws IOException {
        String filename = switch (type.toLowerCase()) {
            case "user_excel" -> "user_import_template.xlsx";
            case "user_word" -> "contract_template.docx";
            default -> throw new IllegalArgumentException("不支持的模板类型");
        };

        ClassPathResource resource = new ClassPathResource("templates/" + filename);
        if (!resource.exists()) return ResponseEntity.notFound().build();

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename*=UTF-8''" + URLEncoder.encode(filename, StandardCharsets.UTF_8))
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(resource.contentLength())
                .body(resource);
    }

    private void writeResponse(XWPFDocument doc, HttpServletResponse response, String filename) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
        doc.write(response.getOutputStream());
    }
}